package ithink.link.base.zk;

import ithink.link.base.service.IConfigMonitor;
import org.I0Itec.zkclient.IZkStateListener;
import org.I0Itec.zkclient.ZkClient;
import org.I0Itec.zkclient.exception.ZkMarshallingError;
import org.I0Itec.zkclient.serialize.ZkSerializer;
import org.apache.zookeeper.Watcher;

/**
 * Created by zaqb on 17-9-10.
 */
public class ZkMonitorFactory {

    public static <T> IConfigMonitor<T> createMonitor(Class<T> type, String zkUrl, String path) {

        Integer sessionTimeout = 1000 * 180;
        Integer connectionTimeout = 30 * 1000;
        ZkClient mainClient  = new ZkClient(zkUrl, sessionTimeout, connectionTimeout);
        mainClient.setZkSerializer(new ZkSerializer() {
            @Override
            public byte[] serialize(Object data) throws ZkMarshallingError {
                return (byte[]) data;
            }
            @Override
            public Object deserialize(byte[] bytes) throws ZkMarshallingError {
                return bytes;
            }
        });
        mainClient.subscribeStateChanges(new IZkStateListener() {
            @Override
            public void handleStateChanged(Watcher.Event.KeeperState state) throws Exception {

            }

            @Override
            public void handleNewSession() throws Exception {

            }

        });
        return new ZkProxy<T>(type, mainClient, path, null);
    }

}
